import sys
import os.path

from .cipher import decrypt
from loguru import logger as logging

from importlib.abc import Loader, MetaPathFinder
from importlib.util import spec_from_file_location

class MyMetaFinder(MetaPathFinder):
    def find_spec(self, fullname, path, target=None):
        if path is None or path == "":
            path = [os.getcwd()] # top level import -- 
        if "." in fullname:
            *parents, name = fullname.split(".")
        else:
            name = fullname
        for entry in path:
            if os.path.isdir(os.path.join(entry, name)):
                # this module has child modules
                filename = os.path.join(entry, name, "__init__.py")
                submodule_locations = [os.path.join(entry, name)]
            else:
                filename = os.path.join(entry, name + ".py")
                submodule_locations = None
            if not os.path.exists(filename):
                continue

            return spec_from_file_location(fullname, filename, loader=MyLoader(filename),
                submodule_search_locations=submodule_locations)

        return None # we don't know how to import this

class MyLoader(Loader):
    def __init__(self, filename):
        self.filename = filename

    def create_module(self, spec):
        return None # use default module creation semantics

    def exec_module(self, module):
        with open(self.filename) as f:
            data = f.read()

        filename = self.filename
        #logging.info(f'myloader filename: {self.filename}, module: {module}')
        if filename.endswith('configuration_instruct.py') or filename.endswith('modeling_instruct.py') or filename.endswith('processing_instruct.py')\
            or filename.endswith('tokenization_llm.py') or filename.endswith('modeling_taichu.py') or filename.endswith('quantizer.py'):
            logging.info(f'filename: {self.filename}, module: {module}')
            data = decrypt(data)
            #with open(filename, 'w') as f:
                ##f.write(data)

        exec(data, vars(module))

def install():
    """Inserts the finder into the import machinery"""
    sys.meta_path.insert(0, MyMetaFinder())
    pass

def uninstall():
    del(sys.meta_path[0])
    pass
